package com.oos.zone.wechat.cp.bean;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.XmlUtils;
import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import me.chanjar.weixin.cp.util.xml.XStreamTransformer;

import java.io.Serializable;

/**
 * 微信推送过来的消息，也是同步回复给用户的消息，xml格式 （预留WxCpXmlMessage类，组件更新迭代慢慢于微信接口时启用）
 **/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
@XStreamAlias("xml")
public class MyWxCpXmlMessage extends WxCpXmlMessage {

    @XStreamAlias("Alias")
    @XStreamConverter(value = XStreamCDataConverter.class)
    private String alias;

    @XStreamAlias("BatchJob")
    private BatchJob batchJob = new BatchJob();

    @Data
    public static class BatchJob implements Serializable {

        private static final long serialVersionUID = -7813518641398482933L;

        @XStreamAlias("JobId")
        @XStreamConverter(value = XStreamCDataConverter.class)
        private String jobId;

        @XStreamAlias("JobType")
        @XStreamConverter(value = XStreamCDataConverter.class)
        private String jobType;

        @XStreamAlias("ErrCode")
        private Integer errCode;

        @XStreamAlias("ErrMsg")
        @XStreamConverter(value = XStreamCDataConverter.class)
        private String errMsg;
    }

    protected static MyWxCpXmlMessage fromXml(String xml) {
        //修改微信变态的消息内容格式，方便解析
        xml = xml.replace("</PicList><PicList>", "");
        final MyWxCpXmlMessage xmlMessage = XStreamTransformer.fromXml(MyWxCpXmlMessage.class, xml);
        xmlMessage.setAllFieldsMap(XmlUtils.xml2Map(xml));
        return xmlMessage;
    }

    /**
     * 从加密字符串转换.
     */
    public static MyWxCpXmlMessage fromEncryptedXml(String encryptedXml, WxCpConfigStorage wxCpConfigStorage,
                                                    String timestamp, String nonce, String msgSignature) {
        WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage);
        String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml);
        log.debug("解密后的原始xml消息内容：{}", plainText);
        return fromXml(plainText);
    }

    @Override
    public String toString() {
        return super.toString();
    }

}
